package com.baidu.littlepainter.fragments.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.OnApplyWindowInsetsListener
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.baidu.littlepainter.utils.KeyboardAnimation

abstract class BaseFragment<T: ViewBinding>: Fragment() {
    private lateinit var _binding:T
    val mBinding:T
        get() = _binding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = initBinding()
        return _binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initKeyboardListener()
        initEeyboardEvent()
    }
    private fun initEeyboardEvent(){
        mBinding.root.setOnClickListener {
            val insets = ViewCompat.getRootWindowInsets(mBinding.root)
            insets?.also{
                if (insets.isVisible(WindowInsetsCompat.Type.ime())){
                    //隐藏键盘
                   mBinding.root.windowInsetsController?.hide(WindowInsetsCompat.Type.ime())
                }
            }
        }
    }
    private fun initKeyboardListener(){
        val view = initKeyboardAnimationView()
        if (view != null) {
            ViewCompat.setOnApplyWindowInsetsListener(view, object :
                OnApplyWindowInsetsListener {
                override fun onApplyWindowInsets(
                    v: View,
                    insets: WindowInsetsCompat
                ): WindowInsetsCompat {
                    //键盘动画
                    KeyboardAnimation.setupKeyboardAnimation(view, 100)
                    return insets
                }
            })
        }
    }

    open fun initKeyboardAnimationView():View?{
        return null
    }
    abstract fun initBinding(): T
    open fun initView() {}


}